package org.nxl.ExceptionDetector;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpEntity;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class App 
{
    public static void main( String[] args ) throws FileNotFoundException
    {
        //load config
    	Yaml yaml = new Yaml(new Constructor(Config.class));
    	InputStream inputStream = new FileInputStream("config.yml");
    	Config config = yaml.load(inputStream);

   	
    	final List<Task> taskList = new ArrayList<Task>();
    	BlockingQueue<Map> queue = new ArrayBlockingQueue<Map>(10000);
    	for(AppInfo app : config.getApps()) {
    		for(String exception : app.getExceptions()) {
    			Task task = new Task();
    			task.setApp(app.getAppName());
    			task.setUrl("http://" + app.getAddress() + ":" + app.getPort() + "/api");
    			task.setException(exception);
    			task.setQueue(queue);
    			taskList.add(task);
    		}
    	}
    	
    	final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(50, 100, 10000, TimeUnit.DAYS, new ArrayBlockingQueue<Runnable>(1000));
    	ScheduledThreadPoolExecutor scheduledExecutor = new ScheduledThreadPoolExecutor(1);
    	scheduledExecutor.scheduleAtFixedRate(new Runnable() {

			public void run() {
				for(Task task : taskList) {
					threadPool.execute(task);
				}
			}
    	}, 2, 2, TimeUnit.SECONDS);
    	
    	
    	ExecutorService es = Executors.newSingleThreadExecutor();
    	es.execute(new Consumer(config.getDbPath(), queue));
    	
    	
    }
}
